package com.auto.autoapp.ui.activity

import android.content.Intent
import android.graphics.Rect
import android.view.View
import android.widget.EditText
import android.widget.Toast
import com.auto.autoapp.base.BaseActivity
import com.auto.autoapp.databinding.ActivityWatchVideoCommentBinding
import com.auto.autoapp.model.WatchVideoCommentSetting
import com.auto.autoapp.services.FloatingWindowService
import com.auto.autoapp.task.AccountRaiseTask
import com.auto.autoapp.task.WatchVideoCommentTask
import com.auto.autoapp.util.SpUtil
import com.auto.autoapp.widgets.SettingItemView
import com.auto.autoapp.widgets.SimpleToolbar
import com.ven.assists.stepper.StepManager

class WatchVideoCommentActivity : BaseActivity() {
    private lateinit var binding: ActivityWatchVideoCommentBinding
    override fun provideView(): View {
        binding = ActivityWatchVideoCommentBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun configToolbar(toolbar: SimpleToolbar) {
        super.configToolbar(toolbar)
        toolbar.setTitle(intent.getStringExtra("title"))
    }

    override fun onInit() {
        // 填充已保存值（聚合对象）
        val vc = SpUtil.getWatchVideoCommentSetting()
        binding.sivVideoList.setValues(vc.videoList)
        binding.sivIncludeKeywords.setValues(listOf(vc.includeKeywords))
        binding.sivExcludeKeywords.setValues(listOf(vc.excludeKeywords))
        binding.sivReplyList.setValues(vc.replyList)
        binding.sivIntervalDays.setValues(listOf(vc.intervalDays.toString()))
        binding.sivMaxCommentCount.setValues(listOf(vc.maxCommentCount.toString()))

        // 焦点滚动适配
        attachFocusScroll(binding.sivVideoList)
        attachFocusScroll(binding.sivIncludeKeywords)
        attachFocusScroll(binding.sivExcludeKeywords)
        attachFocusScroll(binding.sivReplyList)

        binding.btnConfirm.setOnClickListener {
            val videos =
                binding.sivVideoList.getValues().map { it.trim() }.filter { it.isNotEmpty() }
            val includeKw = binding.sivIncludeKeywords.getValues().firstOrNull()?.trim().orEmpty()
            val excludeKw = binding.sivExcludeKeywords.getValues().firstOrNull()?.trim().orEmpty()
            val intervalDays =
                binding.sivIntervalDays.getValues().firstOrNull()?.trim().orEmpty().toIntOrNull()
            val maxCommentCount =
                binding.sivMaxCommentCount.getValues().firstOrNull()?.trim().orEmpty().toIntOrNull()
            val replies =
                binding.sivReplyList.getValues().map { it.trim() }.filter { it.isNotEmpty() }

            clearError(binding.sivVideoList)
            clearError(binding.sivIncludeKeywords)
            clearError(binding.sivExcludeKeywords)
            clearError(binding.sivReplyList)

            var hasError = false
            if (videos.isEmpty()) {
                binding.sivVideoList.findViewById<EditText>(com.auto.autoapp.R.id.et_value)?.error =
                    "请至少填写一个视频地址"
                hasError = true
            }

            if (hasError) {
                Toast.makeText(this, "请修正标红项后再确认", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            // 保存到本地（聚合对象，关键字可留空）
            val setting = WatchVideoCommentSetting(
                videoList = videos,
                includeKeywords = includeKw,
                excludeKeywords = excludeKw,
                replyList = replies,
                intervalDays = intervalDays ?: 10,
                maxCommentCount = maxCommentCount ?: 20
            )
            SpUtil.setWatchVideoCommentSetting(setting)

            if (FloatingWindowService.getInstance() == null) {
                val intent = Intent(this, FloatingWindowService::class.java)
                intent.action = "SHOW_FLOATING_WINDOW"
                startService(intent)
            }

            StepManager.isStop = true
            StepManager.execute(WatchVideoCommentTask::class.java, 1, begin = true)

        }
    }

    private fun clearError(item: SettingItemView) {
        item.findViewById<EditText>(com.auto.autoapp.R.id.et_value)?.error = null
    }

    private fun attachFocusScroll(item: SettingItemView) {
        item.setOnChildFocusListener { target ->
            scrollToView(target)
        }
    }

    private fun scrollToView(target: View) {
        binding.scrollContent.post {
            val rect = Rect()
            target.getDrawingRect(rect)
            binding.scrollContent.offsetDescendantRectToMyCoords(target, rect)
            val y = (rect.top - dp(24)).coerceAtLeast(0)
            binding.scrollContent.smoothScrollTo(0, y)
        }
    }

    private fun dp(value: Int): Int {
        val d = resources.displayMetrics.density
        return (value * d).toInt()
    }
}